import os
import csv
import sys
from typing import List, Dict, Optional

class AccountManager:
    """管理 Outlook 账号的类"""
    
    DEFAULT_ACCOUNTS_FILE = "outlook_accounts.csv"
    
    @staticmethod
    def check_accounts_file(file_path: str = DEFAULT_ACCOUNTS_FILE) -> bool:
        """检查账号文件是否存在"""
        return os.path.exists(file_path)
    
    @staticmethod
    def create_accounts_file(file_path: str = DEFAULT_ACCOUNTS_FILE) -> None:
        """创建空的账号文件模板"""
        with open(file_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['email', 'password'])
            writer.writerow(['example@outlook.com', 'your_password'])
        
        print(f"[AccountManager] 已创建账号文件模板: {file_path}")
        print("[AccountManager] 请在文件中填入您的 Outlook 账号和密码，然后重新运行程序")
    
    @staticmethod
    def load_accounts(file_path: str = DEFAULT_ACCOUNTS_FILE) -> List[Dict[str, str]]:
        """加载账号文件中的所有账号"""
        if not AccountManager.check_accounts_file(file_path):
            return []
        
        accounts = []
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                # 检查文件第一行是否以 // 开头（注释）
                first_line = f.readline().strip()
                f.seek(0)  # 重置文件指针
                
                if first_line.startswith('//'):
                    # 跳过第一行，自定义处理格式
                    next(f)  # 跳过注释行
                    for line in f:
                        line = line.strip()
                        if not line or line.startswith('//'):
                            continue
                        parts = line.split(',')
                        if len(parts) >= 2:
                            accounts.append({'email': parts[0], 'password': parts[1]})
                else:
                    # 使用标准CSV格式
                    reader = csv.DictReader(f)
                    for row in reader:
                        if 'email' in row and 'password' in row:
                            accounts.append({
                                'email': row['email'],
                                'password': row['password']
                            })
        except Exception as e:
            print(f"[AccountManager] 读取账号文件失败: {str(e)}")
            return []
        
        print(f"[AccountManager] 已从 {file_path} 加载 {len(accounts)} 个账号")
        return accounts
    
    @staticmethod
    def remove_account(file_path: str = DEFAULT_ACCOUNTS_FILE, email: str = None) -> bool:
        """从账号文件中删除指定账号"""
        if not AccountManager.check_accounts_file(file_path) or not email:
            return False
        
        accounts = AccountManager.load_accounts(file_path)
        updated_accounts = [account for account in accounts if account['email'] != email]
        
        if len(accounts) == len(updated_accounts):
            print(f"[AccountManager] 未找到要删除的账号: {email}")
            return False
        
        # 重写账号文件
        with open(file_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=['email', 'password'])
            writer.writeheader()
            writer.writerows(updated_accounts)
        
        print(f"[AccountManager] 已删除账号: {email}")
        return True
    
    @staticmethod
    def add_account(email: str, password: str, file_path: str = DEFAULT_ACCOUNTS_FILE) -> bool:
        """添加新账号到账号文件"""
        if not email or not password:
            return False
        
        accounts = AccountManager.load_accounts(file_path)
        
        # 检查账号是否已存在
        for account in accounts:
            if account['email'] == email:
                print(f"[AccountManager] 账号已存在: {email}")
                return False
        
        # 添加新账号
        accounts.append({'email': email, 'password': password})
        
        # 写入账号文件
        with open(file_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=['email', 'password'])
            writer.writeheader()
            writer.writerows(accounts)
        
        print(f"[AccountManager] 已添加新账号: {email}")
        return True
